// 结构件核价
<script setup lang="ts">
// 
import BomForm from './components/DetailForm.vue'
import CustomDetailForm from './components/DetailForm2.vue'

// 导入所需的Vue组件和工具函数
import { nextTick, onMounted, onUnmounted, reactive, ref, computed } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'

// 导入报价单相关的类型定义和API
import {
  Quotation,
  QuotationListParam,
  QuotationShare,
  QuotationUpdateStatus,
  QuotationPrintl,
  QuotationDetailVo,
  ExportFieldInfo,
  ExportRequest
} from '@/api/quotation/type.ts'
import {
  getListApi,
  updateStatusApi,
  updateQuotationShareApi,
  printQuotationApi,
  importQuotationApi,
  exportQuotationApi,
  exportCustomQuotationApi,
  getExportFieldsApi,
  downloadQuotationTemplateApi,
  deleteApi,
  batchDeleteApi,
  batchUpdateStatusApi,
  batchCopyApi
} from '@/api/quotation/index.ts'

// 导入项目相关的类型定义和API
import { ProjectDocument, ProjectDocumentListParam } from "@/api/project/type.ts"
import { getProjectDocumentListApi } from "@/api/project"

// 导入历史报价单相关API
import { saveStructureQuotationApi } from "@/api/historicalQuotation"

// 导入日期格式化工具
import dayjs from 'dayjs'

// 导入图标组件
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete,
  Money,
  Document,
  Upload,
  Download,
  Setting,
  Check,
  InfoFilled,
  Close,
  Switch
} from '@element-plus/icons-vue'

import SysDialog from '@/components/dialog/SysDialog.vue'
import useDialog from '@/hooks/useDialog'
import useInstance from '@/hooks/useInstance'
import { handleError } from '@/utils/errorHandler'
import { formatPrice, formatNumber } from '@/utils/formatter'
// 使用dialog钩子获取弹窗控制方法
const { dialog, onShow, onClose } = useDialog()
const { global } = useInstance()

// 定义表格高度，用于自适应布局
const tableHeight = ref(0)

// 表格数据相关的响应式变量
const tableData = ref<any[]>([]) // 表格数据
const loading = ref(false) // 加载状态
// 分页相关数据
const paginationData = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})

// 查询表单对象
const searchForm = reactive(<QuotationListParam>{
  projectId: undefined,
  activate: undefined,
  name: undefined,
  specification: undefined,
})

// 修改报价单的状态
const updateStatus = reactive(<QuotationUpdateStatus>{
  id: undefined, // 报价单ID
  activate: undefined, // 状态
})

// 分摊金额参数
const quotationShare = reactive(<QuotationShare>{
  ids: [], // 选中的报价单
  type: undefined, // 分摊类型
  price: undefined, // 分摊金额
})

// 导入导出相关变量
const fileInputRef = ref<HTMLInputElement>()

// 导入结果对话框
const importResultDialog = reactive({
  visible: false,
  result: {
    successCount: 0,
    failCount: 0,
    formatErrorCount: 0,
    saveErrorCount: 0,
    errorDetails: [] as string[]
  }
})
const exportFieldList = ref<ExportFieldInfo[]>([])
const selectedExportFields = ref<string[]>([])
const exportDialog = reactive({
  visible: false
})
const fieldSearchText = ref('')

// 过滤后的导出字段列表
const filteredExportFields = computed(() => {
  if (!fieldSearchText.value) {
    return exportFieldList.value
  }
  return exportFieldList.value.filter(field =>
    field.displayName.toLowerCase().includes(fieldSearchText.value.toLowerCase()) ||
    field.fieldName.toLowerCase().includes(fieldSearchText.value.toLowerCase())
  )
})

// 标志位：防止初始化时触发
const isDataLoaded = ref(false)

// 查询方法 - 重置页码并获取数据
const search = () => {
  paginationData.currentPage = 1
  getTableData()
}

// 重置查询条件
const reset = () => {
  searchForm.projectId = undefined
  searchForm.activate = undefined
  searchForm.name = undefined
  searchForm.specification = undefined
  selectedProject.value = null
  search()
}

// 获取表格数据的核心方法
const getTableData = async () => {
  loading.value = true
  try {
    // 设置分页参数
    searchForm.page = paginationData.currentPage
    searchForm.limit = paginationData.pageSize
    // 调用API获取数据
    let res = await getListApi(searchForm)
    if (res && res.data) {
      tableData.value = res.data.list
      paginationData.total = res.data.total
      
      // 注：activate字段从后端返回的是Integer类型（0或1）
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 生命周期钩子 - 组件挂载时初始化数据和设置表格高度
onMounted(() => {
  getTableData()
  // 获取导出字段列表
  getExportFieldList()
  nextTick(() => {
    tableHeight.value = window.innerHeight - 268
    // 设置数据加载完成标志
    isDataLoaded.value = true
  })
})

// 监听窗口大小变化，动态调整表格高度
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
}

// 组件挂载时添加窗口大小变化监听
onMounted(() => {
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除监听器
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 报价单表单显示控制
const showForm = ref(false) // 控制表单显示/隐藏
const formMode = ref<string>('add') // 表单模式：add/edit/view
const Id = ref<number>() // 当前操作的报价单 ID

// 非标结构件表单显示控制
const showCustomForm = ref(false) // 控制非标结构件表单显示/隐藏
const customFormMode = ref<string>('add') // 非标结构件表单模式：add/edit/view
const customFormId = ref<number>() // 当前操作的非标结构件 ID

// 新增BOM
const handleAdd = () => {
  formMode.value = 'add'
  Id.value = undefined
  showForm.value = true
}

// 新增非标结构件
const handleAddCustom = () => {
  customFormMode.value = 'add'
  customFormId.value = undefined
  showCustomForm.value = true
}

// 编辑BOM
const handleEdit = (row: any) => {
  // 检查核价模块状态：如果已失效则不允许编辑
  // 注：activate字段是Integer类型（0或1），需要转换为数字进行比较
  if (Number(row.activate) !== 1) {
    ElMessage.warning('该核价模块已失效，不允许编辑操作1')
    return
  }
  formMode.value = 'edit'
  Id.value = row.id
  showForm.value = true
}

// 非标编辑
const handleCustomEdit = (row: any) => {
  // 检查核价模块状态：如果已失效则不允许编辑
  if (Number(row.activate) !== 1) {
    ElMessage.warning('该核价模块已失效，不允许编辑操作2')
    return
  }
  customFormMode.value = 'edit'
  customFormId.value = row.id
  showCustomForm.value = true
}

// 查看BOM详情
const handleView = (row: any) => {
  formMode.value = 'view'
  Id.value = row.id
  showForm.value = true
}

// 保存成功后的回调
const handleSaveSuccess = () => {
  showForm.value = false
  getTableData()
}

// 取消操作
const handleCancel = () => {
  showForm.value = false
}

// 非标结构件保存成功后的回调
const handleCustomSaveSuccess = () => {
  showCustomForm.value = false
  getTableData()
}

// 非标结构件取消操作
const handleCustomCancel = () => {
  showCustomForm.value = false
}

// 激活 失效 - 已移除单个切换功能，保留批量操作功能
// const activateChange = async (val: boolean, id: number) => {
//   // 如果数据还没加载完成，不执行更新操作
//   if (!isDataLoaded.value) return
//   
//   updateStatus.id = id
//   updateStatus.activate = val
//   try {
//     const result = await updateStatusApi(updateStatus)
//     ElMessage.success('操作成功')
//   } catch (error) {
//     ElMessage.error('操作失败')
//   }
// }

// 文件上传处理
const triggerFileUpload = () => {
  fileInputRef.value?.click()
}

const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  
  if (!file) return
  
  const loading = ElMessage({
    message: '正在导入数据...',
    type: 'info',
    duration: 0
  })

  importQuotationApi(file)
    .then((res: any) => {
      loading.close()
      
      // 处理导入结果
      if (res.data && typeof res.data === 'object') {
        const result = res.data
        console.log('导入结果原始数据:', result)
        
        // 逐个赋值以确保响应式更新
        importResultDialog.result.successCount = result.successCount || 0
        importResultDialog.result.failCount = result.failCount || 0
        importResultDialog.result.formatErrorCount = result.formatErrorCount || 0
        importResultDialog.result.saveErrorCount = result.saveErrorCount || 0
        importResultDialog.result.errorDetails = result.errorDetails || []
        
        console.log('赋值后的对话框数据:', importResultDialog.result)
        console.log('对话框可见状态:', importResultDialog.visible)
        if (result.successCount > 0) {
          if (result.failCount > 0) {
            // 部分成功
            ElMessage.warning(`部分导入成功：成功${result.successCount}条，失败${result.failCount}条`)
            showImportResultDialog()
          } else {
            // 全部成功
            ElMessage.success(`全部导入成功：${result.successCount}条`)
          }
          getTableData() // 刷新列表
        } else {
          // 全部失败
          ElMessage.error(`导入失败：${result.failCount}条记录有错误`)
          showImportResultDialog()
        }
      } else {
        // 兼容旧版本返回格式
        ElMessage.success(res.message || '导入成功')
        getTableData()
      }
      
      // 清空文件选择
      if (fileInputRef.value) {
        fileInputRef.value.value = ''
      }
    })
    .catch((error: any) => {
      loading.close()
      handleError(error, '导入失败')
      
      // 清空文件选择
      if (fileInputRef.value) {
        fileInputRef.value.value = ''
      }
    })
}

// 显示导入结果对话框
const showImportResultDialog = () => {
  console.log('准备显示导入结果对话框')
  console.log('当前对话框数据:', importResultDialog.result)
  importResultDialog.visible = true
  console.log('设置对话框可见状态为:', importResultDialog.visible)
}

// 关闭导入结果对话框
const closeImportResultDialog = () => {
  importResultDialog.visible = false
}

// 导出数据
const handleExport = async () => {
  try {
    loading.value = true
    searchForm.limit = 9999

    await exportQuotationApi(searchForm)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 下载模板
const handleDownloadTemplate = async () => {
  try {
    loading.value = true
    await downloadQuotationTemplateApi()
    ElMessage.success('模板下载成功')
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载模板失败')
  } finally {
    loading.value = false
  }
}

// 获取可导出字段列表
const getExportFieldList = async () => {
  try {
    const res = await getExportFieldsApi()
    if (res.code === 200) {
      exportFieldList.value = res.data
    }
  } catch (error) {
    console.error('获取导出字段列表失败:', error)
  }
}

// 打开自定义导出弹窗
const openExportDialog = () => {
  exportDialog.visible = true
  // 默认选中所有字段
  selectedExportFields.value = exportFieldList.value.map(field => field.fieldName)
}

// 关闭自定义导出弹窗
const closeExportDialog = () => {
  exportDialog.visible = false
  fieldSearchText.value = ''
}

// 切换字段选中状态
const toggleField = (fieldName: string) => {
  const index = selectedExportFields.value.indexOf(fieldName)
  if (index > -1) {
    selectedExportFields.value.splice(index, 1)
  } else {
    selectedExportFields.value.push(fieldName)
  }
}

// 全选/取消全选导出字段
const handleSelectAllFields = (checked: boolean) => {
  if (checked) {
    selectedExportFields.value = exportFieldList.value.map(field => field.fieldName)
  } else {
    selectedExportFields.value = []
  }
}

// 确认自定义导出
const confirmCustomExport = async () => {
  if (selectedExportFields.value.length === 0) {
    ElMessage.warning('请至少选择一个导出字段')
    return
  }
  
  try {
    loading.value = true
    // 移除分页参数，确保导出所有数据
    const { page, limit, ...exportParams } = searchForm
    
    // 检查是否有查询条件
    const hasConditions = Object.keys(exportParams).some(key => {
      const value = (exportParams as any)[key]
      return value !== undefined && value !== null && value !== ''
    })
    
    if (hasConditions) {
      console.log('自定义导出-按查询条件导出数据:', exportParams)
      ElMessage.info('正在导出符合当前查询条件的数据...')
    } else {
      console.log('自定义导出-导出全部数据')
      ElMessage.info('正在导出全部数据...')
    }
    
    searchForm.limit = 9999
    await exportCustomQuotationApi({
      fields: selectedExportFields.value,
      searchParam: exportParams as any
    })
    
    ElMessage.success('导出成功')
    closeExportDialog()
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

import { getListApi as getColorListApi } from '@/api/color'
import { getListApi as getCustomerListApi } from '@/api/companyCustomer'
import type { Color } from '@/api/color/type'
import type { CompanyCustomer } from '@/api/companyCustomer/type'
import ArchiveSelector from '@/components/common/ArchiveSelector.vue'

// 项目选择器相关数据
const projectSelectorVisible = ref(false)
const selectedProject = ref<ProjectDocument | null>(null)
// 项目状态映射
const statusOptions = [
  { value: 0, label: '进行中' },
  { value: 1, label: '已完成' },
  { value: 2, label: '已暂停' },
  { value: 3, label: '已取消' },
]
// 项目选择器搜索字段配置
const projectSearchFields = [
  { label: '项目名称', prop: 'name', type: 'input' as const },
  { label: '项目编号', prop: 'code', type: 'input' as const },
  { label: '客户名称', prop: 'customer', type: 'input' as const },
  {
    label: '项目状态',
    prop: 'status',
    type: 'select' as const,
    options: statusOptions,
  },
]

// 项目选择器表格列配置
const projectTableColumns = [
  { prop: 'name', label: '项目名称', width: 250 },
  { prop: 'code', label: '项目编号', width: 250 },
  { prop: 'customer', label: '客户名称', width: 250 },
  { prop: 'manager', label: '项目经理', width: 200 },
]

// 获取项目列表数据的API方法
const getProjectList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: ProjectDocumentListParam = {
      name: params.name,
      code: params.code,
      customer: params.customer,
      status: params.status,
      page: params.page || 1,
      limit: params.limit || 10,
    }

    // 调用项目列表API - 使用真实API
    return await getProjectDocumentListApi(queryParams)
  } catch (error) {
    console.error('获取项目列表失败:', error)
    return { data: { list: [], total: 0 } }
  }
}

// 打开项目选择器
const openProjectSelector = () => {
  projectSelectorVisible.value = true
}

// 处理项目选择确认
const handleProjectSelect = (project: ProjectDocument) => {
  selectedProject.value = project
  console.log('选择的项目:', project)
  searchForm.projectId = project.id
}
// 表格多选选中数据
const multipleSelection = ref<any[]>([])

// 表格多选事件
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
  quotationShare.ids = val.map((item) => item.id).filter(Boolean) as number[]
}

// 分摊类型选项
const shareTypes = [
  { label: '包装费', value: 1 },
  { label: '运输费', value: 2 },
  { label: '实施费', value: 3 },
  { label: '其他运营成本', value: 4 },
]

// 显示分摊弹框
const showShareDialog = () => {
  if (quotationShare.ids.length === 0) {
    ElMessage.warning('请先选择需要分摊的报价单')
    return
  }
  
  // 检查选中的记录中是否有已失效的
  const invalidRecords = multipleSelection.value.filter(item => Number(item.activate) !== 1)
  if (invalidRecords.length > 0) {
    ElMessage.warning(`选中的记录中有${invalidRecords.length}条已失效，不允许分摊费用操作`)
    return
  }
  
  dialog.title = '分摊费用'
  dialog.width = 500
  dialog.height = 250
  dialog.visible = true
}

// 提交分摊
const submitShare = async () => {
  if (!quotationShare.type) {
    ElMessage.warning('请选择分摊类型')
    return
  }
  if (!quotationShare.price) {
    ElMessage.warning('请输入分摊金额')
    return
  }
  try {
    await updateQuotationShareApi(quotationShare)
    ElMessage.success('分摊成功')
    dialog.visible = false
    // 重置表单
    quotationShare.type = undefined
    quotationShare.price = undefined
    // 刷新列表
    getTableData()
  } catch (error) {
    console.error('分摊失败:', error)
  }
}

// 单个删除
const deleteOne = async (id: number) => {
  try {
    // 查找要删除的记录，检查其状态
    const row = tableData.value.find(item => item.id === id)
    if (row && Number(row.activate) !== 1) {
      ElMessage.warning('该核价模块已失效，不允许删除操作')
      return
    }
    
    await global.$myConfirm('确定要删除该核价单吗，是否继续?')
    await deleteApi(id)
    ElMessage.success('删除成功')
    getTableData()
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 批量删除
const batchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择需要删除的记录')
    return
  }
  
  // 检查选中的记录中是否有已失效的
  const invalidRecords = multipleSelection.value.filter(item => Number(item.activate) !== 1)
  if (invalidRecords.length > 0) {
    ElMessage.warning(`选中的记录中有${invalidRecords.length}条已失效，不允许删除操作`)
    return
  }
  
  try {
    await global.$myConfirm(`确定要删除选中的${multipleSelection.value.length}条记录吗？`)
    const ids = multipleSelection.value.map(item => item.id).filter(Boolean) as number[]
    await batchDeleteApi(ids)
    ElMessage.success('批量删除成功')
    getTableData()
    // 清空选择
    multipleSelection.value = []
  } catch (error) {
    console.error('批量删除失败:', error)
    ElMessage.error('批量删除失败')
  }
}

// 批量失效
const batchDeactivate = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择需要失效的记录')
    return
  }
  
  try {
    await global.$myConfirm(`确定要将选中的${multipleSelection.value.length}条记录设为失效吗？`)
    const ids = multipleSelection.value.map(item => item.id).filter(Boolean) as number[]
    await batchUpdateStatusApi({ ids, activate: 0 })
    ElMessage.success('批量失效成功')
    getTableData()
    // 清空选择
    multipleSelection.value = []
  } catch (error) {
    console.error('批量失效失败:', error)
    ElMessage.error('批量失效失败')
  }
}

// 批量生效
const batchActivate = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择需要生效的记录')
    return
  }
  
  try {
    await global.$myConfirm(`确定要将选中的${multipleSelection.value.length}条记录设为生效吗？`)
    const ids = multipleSelection.value.map(item => item.id).filter(Boolean) as number[]
    await batchUpdateStatusApi({ ids, activate: 1 })
    ElMessage.success('批量生效成功')
    getTableData()
    // 清空选择
    multipleSelection.value = []
  } catch (error) {
    console.error('批量生效失败:', error)
    ElMessage.error('批量生效失败')
  }
}

// 添加报价单弹窗相关状态
const quotationDialog = reactive({
  visible: false,
  title: '报价单',
  width: 900,
  height: 600,
  projectId: undefined as number | undefined // 添加projectId字段
})

// 批量复制弹窗相关状态
const batchCopyDialog = reactive({
  visible: false,
  title: '批量复制',
  width: 500,
  height: 300
})

// 批量复制选择的项目
const batchCopySelectedProject = ref<ProjectDocument | null>(null)

// 批量复制项目选择器
const batchCopyProjectSelectorVisible = ref(false)

// 当前报价单信息
const quotationPrintl = ref<QuotationPrintl | null>(null)

// 格式化金额为大写中文
const convertToChinese = (money: number) => {
  if (money === 0) {
    return '零元整'
  }
  
  const fraction = ['角', '分']
  const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  const unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟']
  ]
  const head = money < 0 ? '负' : ''
  
  money = Math.abs(money)
  
  let s = ''
  
  for (let i = 0; i < fraction.length; i++) {
    s += (digit[Math.floor(money * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '')
  }
  
  s = s || '整'
  
  money = Math.floor(money)
  
  for (let i = 0; i < unit[0].length && money > 0; i++) {
    let p = ''
    for (let j = 0; j < unit[1].length && money > 0; j++) {
      p = digit[money % 10] + unit[1][j] + p
      money = Math.floor(money / 10)
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  }
  
  return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')
}

// 格式化金额为货币格式
const formatCurrency = (value: number) => {
  return '¥' + value.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 打印报价单方法
const printQuotation = () => {
  const printWindow = window.open('', 'PRINT', 'height=800,width=1200')
  if (!printWindow) {
    ElMessage.error('无法打开打印窗口，请检查浏览器设置')
    return
  }
  
  // 获取logo的完整URL
  const logoURL = new URL('../../../assets/logo.png', import.meta.url).href
  
    // 创建表格行HTML
    let tableRowsHtml = ''
    const items = quotationPrintl.value?.children || []
    
    items.forEach((item, index) => {
      tableRowsHtml += `
        <tr>
          <td>${index + 1}</td>
          <td>${item.name || ''}</td>
          <td>${item.specification || ''}</td>
          <td>${item.quantity || ''}</td>
          <td>${item.unit || ''}</td>
          <td>¥ ${item.unitPrice ? item.unitPrice.toFixed(2) : '0.00'}</td>
          <td>${item.totalPrice ? item.totalPrice.toFixed(2) : '0.00'}</td>
          <td>${item.remark || ''}</td>
        </tr>
      `
    })
    
    // 计算总金额
    const totalPrice = items.reduce((sum, item) => sum + (item.totalPrice || 0), 0)
    // 总金额大写
    const totalPriceInChinese = convertToChinese(totalPrice)
    
    const currentDate = new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '/')
    
  // 构建打印内容
  let printContent = `
      <html>
        <head>
          <title>报价单</title>
          <style>
            body { 
              width: 100%; 
              margin: 0; 
              padding: 0;
              font-family: SimSun, serif;
            }
            .quotation-wrapper {
              padding: 20px;
              max-width: 900px;
              margin: 0 auto;
            }
            .quotation-header {
              position: relative;
              margin-bottom: 20px;
              text-align: center;
            }
            .company-logo {
              position: absolute;
              top: 0;
              right: 0;
              text-align: right;
            }
            .company-logo img {
              max-width: 80px;
              height: auto;
            }
            .company-title {
              font-size: 20px;
              font-weight: bold;
              margin-bottom: 10px;
            }
            .document-title {
              font-size: 22px;
              font-weight: bold;
              margin-bottom: 5px;
            }
            .document-info {
              display: flex;
              justify-content: space-between;
              width: 100%;
            }
            .document-number {
              font-weight: bold;
            }
            .document-date {
              font-size: 14px;
            }
            .certification-info {
              text-align: center;
              color: #e41e2b;
              font-size: 14px;
              margin-bottom: 15px;
              border-bottom: 1px solid #dcdfe6;
              padding-bottom: 10px;
            }
            .info-section {
              margin-bottom: 15px;
            }
            .info-table {
              width: 100%;
              border-collapse: collapse;
              margin-bottom: 15px;
            }
            .info-table td {
              padding: 8px;
              border: 1px solid #000;
            }
            .info-table .label {
              width: 17%;
              text-align: right;
              font-weight: bold;
            }
            .info-table .value {
              width: 35%;
            }
            .note-section {
              margin-bottom: 15px;
            }
            .note-label {
              font-weight: bold;
              margin-bottom: 5px;
            }
            .note-content {
              border: 1px solid #000;
              padding: 10px;
            }
            .note-row {
              display: flex;
              margin-bottom: 10px;
            }
            .note-title {
              font-weight: bold;
              width: 150px;
            }
            .items-section {
              margin-bottom: 15px;
            }
            .quotation-table {
              margin: 16px 0;
              font-size: 12px;
              width: 100%;
              border-collapse: collapse;
            }
            .quotation-table th,
            .quotation-table td {
              padding: 6px;
              border: 1px solid #000;
              text-align: center;
            }
            .quotation-table thead th {
              background-color: #f0f0f0;
              font-weight: bold;
            }
            .quotation-table .total-row {
              background-color: #f0f0f0;
              font-weight: bold;
            }
            .quotation-table .total-row .text-right {
              text-align: right;
            }
            .terms-section {
              margin-top: 15px;
            }
            .terms-list {
              margin-left: 20px;
              padding-left: 0;
            }
            .terms-list li {
              margin-bottom: 5px;
              font-size: 14px;
            }
            .terms-note {
              margin-top: 10px;
              font-size: 14px;
            }
            .quotation-footer {
              margin-top: 24px;
              padding-top: 16px;
              border-top: 1px solid #ebeef5;
              display: flex;
              justify-content: flex-end;
            }
            .print-area {
              display: none !important;
              visibility: hidden !important;
            }
            .total-amount {
              margin-left: auto;
              font-size: 16px;
              font-weight: bold;
              color: #303133;
              text-align: right;
            }
            .el-button {
              display: none !important;
            }
          </style>
        </head>
        <body>
          <div class="quotation-wrapper">
            <div class="quotation-header">
              <div class="company-logo">
                <img src="${logoURL}" alt="公司logo" class="logo-image">
              </div>
              <div class="company-title">
                浙江中扬立库技术有限公司
              </div>
              <div class="document-title">
                报价单
              </div>
                <div class="document-info">
                <div class="document-date"> </div>
                <div class="document-number">NO.${ Math.floor(Math.random() * 1000) + 1 }</div>
              </div>
              <div class="document-info">
                <div class="document-number"> </div>
                <div class="document-date">日期：${currentDate}</div>
              </div>
            </div>
            
            <!-- 公司认证信息 -->
            <div class="certification-info">
              本公司专业生产制造现代仓储物流系统设备，已通过ISO9001质量体系认证、环境管理体系ISO14001
            </div>
            
            <!-- 客户与公司信息 -->
            <div class="info-section">
              <table class="info-table" border="1" cellspacing="0" cellpadding="0">
                <tr>
                  <td class="label">客户名称：</td>
                  <td class="value">${quotationPrintl.value?.customerName || ''}</td>
                  <td class="label">公司：</td>
                  <td class="value">浙江中扬立库技术有限公司</td>
                </tr>
                <tr>
                  <td class="label">联系人：</td>
                  <td class="value">${quotationPrintl.value?.customerPerson || ''}</td>
                  <td class="label">联系人：</td>
                  <td class="value">${quotationPrintl.value?.person || ''}</td>
                </tr>
                <tr>
                  <td class="label">联系方式：</td>
                  <td class="value">${quotationPrintl.value?.customerPhone || ''}</td>
                  <td class="label">联系方式：</td>
                  <td class="value">${quotationPrintl.value?.pPhone || ''}</td>
                </tr>
                <tr>
                  <td class="label">地址：</td>
                  <td class="value">${quotationPrintl.value?.customerAddress || ''}</td>
                  <td class="label">地址：</td>
                  <td class="value">${quotationPrintl.value?.address || ''}</td>
                </tr>
                <tr>
                  <td class="label">传真：</td>
                  <td class="value">${quotationPrintl.value?.customerFax || ''}</td>
                  <td class="label">传真：</td>
                  <td class="value">${quotationPrintl.value?.fax || ''}</td>
                </tr>
                <tr>
                  <td class="label">邮箱：</td>
                  <td class="value">${quotationPrintl.value?.customerEmail || ''}</td>
                  <td class="label">邮箱：</td>
                  <td class="value">${quotationPrintl.value?.email || ''}</td>
                </tr>
              </table>
            </div>
            
            <!-- 备注区域 -->
            <div class="note-section">
              <div class="note-label">备注</div>
              <div class="note-content">
                <div class="note-row">
                  <div class="note-title">货物参数：</div>
                </div>
                <div class="note-row">
                  <div class="note-title">货物简要描述：</div>
                </div>
              </div>
            </div>
            
            <!-- 商品清单 -->
            <div class="items-section">
              <table class="quotation-table" border="1" cellspacing="0" cellpadding="0">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>名称</th>
                    <th>规格型号</th>
                    <th>数量</th>
                    <th>单位</th>
                    <th>单价</th>
                    <th>小计</th>
                    <th>备注</th>
                  </tr>
                </thead>
                <tbody>
                  ${tableRowsHtml}
                  <tr class="total-row">
                    <td colspan="2" class="text-right">总计大写：</td>
                    <td colspan="3">${totalPriceInChinese}</td>
                    <td>总计金额：</td>
                    <td colspan="2">${formatCurrency(totalPrice)}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- 报价条款 -->
            <div class="terms-section">
              <ol class="terms-list">
                <li>以上报价根据国家税率涨幅含增值税发票；</li>
                <li>材质：Q355/Q235。强度标准：GB/50018-2016，屈服强度—235(N/mm2)  抗拉—205(N/mm2)  伸长率31%</li>
                <li>表面处理：脱脂磷化，后采用优质环氧树脂瑞士金马静电喷涂，执行标准：GB 15607-2008</li>
                <li>焊接标准.焊接标准：抗压—300(N/mm2) 抗拉—255(N/mm2) 抗剪—175(N/mm2)</li>
                <li>制造执行标准：CECS23-90(货架设计规范)；Jb/t5323-1991 (钢货架技术条件)；GBJ50017-2003 （高位仓库货架设计标准）；GBT 30675-2014 （阁楼式货架）</li>
                <li>报价单有效期：由于钢材价格波动比较大，此报价有效期：3天。</li>
                <li>钢材供应商；宝钢 日照钢铁 鞍钢 首钢及国内大型钢厂</li>
                <li>保修期：非人为因素保修1年</li>
                <li>付款方式：预付40%，发货付40%，全部到货验收后30天内付20%。</li>
                <li>以上报价按抗震6度计算，地震加速度为0.05g;</li>
              </ol>
              <div class="terms-note">
                注：付款方式为电汇，如承兑付款收取承兑汇票2.5%财务费用（半年期），乙方不接受商业承兑汇票。
              </div>
            </div>
          </div>
        </body>
      </html>
  `
  
  printWindow.document.write(printContent)
    printWindow.document.close()
    printWindow.focus()
    printWindow.print()
    printWindow.close()
    quotationDialog.visible = false
}

// 生成报价单方法
const generateQuotation = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择需要生成报价单的记录')
    return
  }
  
  // 检查选中的记录中是否有已失效的
  const invalidRecords = multipleSelection.value.filter(item => Number(item.activate) !== 1)
  if (invalidRecords.length > 0) {
    ElMessage.warning(`选中的记录中有${invalidRecords.length}条已失效，不允许生成报价单操作`)
    return
  }
  
  try {
    // 获取选中项目的ID
    // 直接从勾选的核价单中获取项目ID
    // 优先使用第一个选中项目的projectId
    let projectId: number | undefined
    
    // 1. 先检查选中项中是否有projectId字段
    const firstItem = multipleSelection.value[0]
    if (firstItem && firstItem.projectId) {
      projectId = firstItem.projectId
    } 
    // 2. 如果没有，尝试从projectName找到对应的项目
    else if (firstItem && firstItem.projectName) {
      // 可能需要从表格数据中查找完整的项目信息
      // 或者使用查询条件中的项目ID
      projectId = searchForm.projectId
    }
    // 3. 如果上述都没有，尝试使用已选择的项目
    else if (selectedProject.value && selectedProject.value.id) {
      projectId = selectedProject.value.id
    }
    
    if (!projectId) {
      ElMessage.warning('未能获取到项目ID，请先选择项目')
      return
    }
    
    // 记录获取的项目ID，用于后续保存操作
    quotationDialog.projectId = projectId
    
    // 获取报价单ID列表
    const ids = multipleSelection.value.map(item => item.id).filter(Boolean)
    if (ids.length === 0) {
      ElMessage.warning('未获取到有效的ID列表')
      return
  }
  
    console.log('生成报价单，使用项目ID:', projectId, '选中的报价单IDs:', ids)
    
    // 调用报价单打印API
    const res = await printQuotationApi(ids)
    if (res.code === 200 && res.data) {
      quotationPrintl.value = res.data
      quotationDialog.visible = true
    } else {
      ElMessage.error(res.msg || '生成报价单失败')
    }
  } catch (err) {
    console.error('生成报价单异常', err)
    ElMessage.error('生成报价单失败')
  }
}

// 批量复制方法
const batchCopy = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择需要复制的记录')
    return
  }
  
  // 允许复制失效数据，复制后自动生效
  
  // 重置选择的项目
  batchCopySelectedProject.value = null
  batchCopyDialog.visible = true
}

// 打开批量复制项目选择器
const openBatchCopyProjectSelector = () => {
  batchCopyProjectSelectorVisible.value = true
}

// 处理批量复制项目选择确认
const handleBatchCopyProjectSelect = (project: ProjectDocument) => {
  batchCopySelectedProject.value = project
  console.log('批量复制选择的项目:', project)
}

// 确认批量复制
const confirmBatchCopy = async () => {
  if (!batchCopySelectedProject.value) {
    ElMessage.warning('请选择目标项目')
    return
  }
  
  try {
    const ids = multipleSelection.value.map(item => item.id).filter(Boolean) as number[]
    
    await global.$myConfirm(`确定要将选中的${multipleSelection.value.length}条记录复制到项目"${batchCopySelectedProject.value.name}"吗？`)
    
    // 调用批量复制API
    const copyData = {
      sourceIds: ids,
      targetProjectId: batchCopySelectedProject.value.id!
    }
    
    const res = await batchCopyApi(copyData)
    if (res.code === 200) {
      ElMessage.success(`成功复制${multipleSelection.value.length}条记录`)
      batchCopyDialog.visible = false
      getTableData() // 刷新列表
      // 清空选择
      multipleSelection.value = []
    } else {
      ElMessage.error(res.msg || '批量复制失败')
    }
  } catch (error) {
    console.error('批量复制失败:', error)
    ElMessage.error('批量复制失败')
  }
}

// 取消批量复制
const cancelBatchCopy = () => {
  batchCopyDialog.visible = false
  batchCopySelectedProject.value = null
}

// 添加保存报价单方法
const saveQuotation = async () => {
  if (!quotationPrintl.value) {
    ElMessage.warning('无报价单数据，无法保存')
    return
  }

  // 获取打印内容
  const contentElement = document.getElementById('quotationContent')
  if (!contentElement) {
    ElMessage.error('获取报价单内容失败')
    return
  }

  // 构建完整的HTML内容，包含样式
  const styleContent = `
    <style>
      body { font-family: SimSun, serif; margin: 0; padding: 0; text-align: center; }
      .quotation-wrapper {
        padding: 20px;
        max-width: 900px;
        margin: 0 auto;
      }
      .quotation-header {
        position: relative;
        margin-bottom: 20px;
        text-align: center;
      }
      .company-logo {
        position: absolute;
        top: 0;
        right: 0;
        text-align: right;
      }
      .company-logo img {
        max-width: 80px;
        height: auto;
      }
      .company-title {
        font-size: 20px;
        font-weight: bold;
        margin-bottom: 10px;
      }
      .document-title {
        font-size: 22px;
        font-weight: bold;
        margin-bottom: 5px;
      }
      .document-info {
        display: flex;
        justify-content: space-between;
        width: 100%;
      }
      .document-number {
        font-weight: bold;
      }
      .document-date {
        font-size: 14px;
      }
      .certification-info {
        text-align: center;
        color: #e41e2b;
        font-size: 14px;
        margin-bottom: 15px;
        border-bottom: 1px solid #dcdfe6;
        padding-bottom: 10px;
      }
      .info-section {
        margin-bottom: 15px;
      }
      .info-table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 15px;
      }
      .info-table td {
        padding: 8px;
        border: 1px solid #000;
      }
      .info-table .label {
        width: 17%;
        text-align: right;
        font-weight: bold;
      }
      .info-table .value {
        width: 35%;
      }
      .note-section {
        margin-bottom: 15px;
      }
      .note-label {
        font-weight: bold;
        margin-bottom: 5px;
      }
      .note-content {
        border: 1px solid #000;
        padding: 10px;
      }
      .note-row {
        display: flex;
        margin-bottom: 10px;
      }
      .note-title {
        font-weight: bold;
        width: 150px;
      }
      .items-section {
        margin-bottom: 15px;
      }
      .quotation-table {
        margin: 16px 0;
        font-size: 12px;
        width: 100%;
        border-collapse: collapse;
      }
      .quotation-table th,
      .quotation-table td {
        padding: 6px;
        border: 1px solid #000;
        text-align: center;
      }
      .quotation-table thead th {
        background-color: #f0f0f0;
        font-weight: bold;
      }
      .quotation-table .total-row {
        background-color: #f0f0f0;
        font-weight: bold;
      }
      .quotation-table .total-row .text-right {
        text-align: right;
      }
      .terms-section {
        margin-top: 15px;
      }
      .terms-list {
        margin-left: 20px;
        padding-left: 0;
      }
      .terms-list li {
        margin-bottom: 5px;
        font-size: 14px;
      }
      .terms-note {
        margin-top: 10px;
        font-size: 14px;
      }
      .quotation-footer {
        margin-top: 24px;
        padding-top: 16px;
        border-top: 1px solid #ebeef5;
        display: flex;
        justify-content: flex-end;
      }
      .print-area {
        display: none !important;
        visibility: hidden !important;
      }
      .total-amount {
        margin-left: auto;
        font-size: 16px;
        font-weight: bold;
        color: #303133;
        text-align: right;
      }
      .el-button {
        display: none !important;
      }
    </style>
  `
  
  // 获取内容并移除按钮
  let htmlContent = contentElement.innerHTML
  // 将按钮部分替换为空
  htmlContent = htmlContent.replace(/<div class="quotation-footer">[\s\S]*?<\/div>/g, '')
  
  // 完整的HTML文档
  const fullContent = `
    <div class="quotation-wrapper">
      ${htmlContent}
    </div>
    ${styleContent}
  `
  
  // 获取项目ID - 优先使用生成报价单时保存的项目ID
  let projectId = quotationDialog.projectId
  
  // 如果没有保存的项目ID，尝试从勾选的核价单获取
  if (!projectId && multipleSelection.value.length > 0) {
    const firstItem = multipleSelection.value[0]
    if (firstItem && firstItem.projectId) {
      projectId = firstItem.projectId
    }
  }
  
  // 如果上述方法都没获取到，尝试从其他地方获取
  if (!projectId) {
    // 尝试从查询表单获取
    if (searchForm.projectId) {
      projectId = searchForm.projectId
    }
    // 尝试从已选择的项目获取
    else if (selectedProject.value && selectedProject.value.id) {
      projectId = selectedProject.value.id
    }
  }
  
  // 最后验证是否获取到项目ID
  if (!projectId) {
    ElMessage.warning('未能获取到项目ID，请重新选择项目后再试')
    return
  }
  
  console.log('保存报价单，使用项目ID:', projectId)
  
  // 构建保存数据
  const saveData = {
    projectId: projectId,
    content: fullContent
  }
  
  // 调用保存API
  try {
    const res = await saveStructureQuotationApi(saveData)
    if (res.code === 200) {
      ElMessage.success('报价单保存成功')
      quotationDialog.visible = false
    } else {
      ElMessage.error(res.msg || '保存报价单失败')
    }
  } catch (err) {
    console.error('保存报价单失败', err)
    ElMessage.error('保存报价单失败')
  }
}

</script>

<template>
  <!-- 左侧列表 -->
  <el-main v-if="!showForm && !showCustomForm">
    <div class="container">
      <!-- 搜索区域 -->
      <el-card class="search-card" shadow="never">
        <div class="search-wrapper">
          <!-- 搜索表单 -->
          <div class="search-form-section">
            <el-form :inline="true" :model="searchForm" ref="queryForm" class="demo-form-inline">
              <el-form-item label="项目名称">
                <el-input 
                  :model-value="selectedProject ? selectedProject.name : ''"
                  placeholder="请选择项目"
                  readonly
                  class="selector-input"
                  style="width: 200px"
                >
                  <template #append>
                    <el-button @click="openProjectSelector" v-permission="['specification:view']">选择</el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="名称">
                <el-input 
                  v-model="searchForm.name"
                  placeholder="请输入名称"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
              <el-form-item label="规格">
                <el-input 
                  v-model="searchForm.specification"
                  placeholder="请输入规格"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
              <el-form-item label="状态">
                <el-select 
                  v-model="searchForm.activate" 
                  placeholder="是否生效"
                  clearable
                  filterable
                  style="width: 120px"
                >
                  <el-option label="生效" :value="1" />
                  <el-option label="失效" :value="0" />
                </el-select>
              </el-form-item>
              <el-form-item class="search-buttons">
                <el-button type="primary" @click="search" class="search-btn" v-permission="['specification:view']">
                  <el-icon><Search /></el-icon>
                  查询
                </el-button>
                <el-button @click="reset" class="reset-btn" v-permission="['specification:view']">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 操作按钮区域 -->
          <div class="action-buttons-section">
            <!-- 批量操作按钮组 -->
            <div class="button-group batch-actions">
              <!-- <el-button type="warning" @click="showShareDialog" :disabled="!quotationShare.ids.length" class="share-btn">
                <el-icon><Money /></el-icon>
                分摊费用
              </el-button> -->
              <el-button type="info" @click="generateQuotation" :disabled="!multipleSelection.length" class="generate-btn" v-permission="['specification:edit']">
                <el-icon><Document /></el-icon>
                生成报价单
              </el-button>
              <el-button type="danger" @click="batchDelete" :disabled="!multipleSelection.length" class="batch-delete-btn" v-permission="['specification:edit']">
                <el-icon><Delete /></el-icon>
                批量删除
              </el-button>
              <el-button type="warning" @click="batchDeactivate" :disabled="!multipleSelection.length" class="batch-deactivate-btn" v-permission="['specification:edit']">
                <el-icon><Close /></el-icon>
                批量失效
              </el-button>
              <el-button type="success" @click="batchActivate" :disabled="!multipleSelection.length" class="batch-activate-btn" v-permission="['specification:edit']">
                <el-icon><Check /></el-icon>
                批量生效
              </el-button>
              <el-button type="primary" @click="batchCopy" :disabled="!multipleSelection.length" class="batch-copy-btn" v-permission="['specification:edit']">
                <el-icon><Document /></el-icon>
                批量复制
              </el-button>
            </div>
            
            <!-- 新增操作按钮组 -->
            <div class="button-group add-actions">
              <el-button type="success" @click="handleAdd" class="add-btn" v-permission="['specification:edit']">
                <el-icon><Plus /></el-icon>
                新增
              </el-button>
              <el-button type="primary" @click="handleAddCustom" class="add-custom-btn" v-permission="['specification:edit']">
                <el-icon><Plus /></el-icon>
                新增非标结构件
              </el-button>
            </div>
            
            <!-- 导入导出按钮组 -->
            <div class="button-group import-export-actions">
              <el-button type="info" @click="handleDownloadTemplate" class="template-btn" v-permission="['specification:view']">
                <el-icon><Download /></el-icon>
                下载模板
              </el-button>
              <el-button type="warning" @click="triggerFileUpload" class="import-btn" v-permission="['specification:edit']">
                <el-icon><Upload /></el-icon>
                导入
              </el-button>
              <el-button type="primary" @click="handleExport" class="export-btn" v-permission="['specification:view']">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
              <el-button type="primary" @click="openExportDialog" class="custom-export-btn" v-permission="['specification:view']">
                <el-icon><Setting /></el-icon>
                自定义导出
              </el-button>
            </div>
          </div>
          
          <!-- 隐藏的文件输入框 -->
          <input
            ref="fileInputRef"
            type="file"
            accept=".xlsx,.xls"
            style="display: none"
            @change="handleFileChange"
          />
        </div>
      </el-card>

      <!-- 数据列表 -->
      <el-card class="list-card" shadow="never">
        <el-table 
          v-loading="loading"
          :data="tableData"
          :height="tableHeight"
          element-loading-text="加载中..."
          element-loading-background="rgba(255, 255, 255, 0.7)"
          style="width: 100%"
          stripe
          border
          @selection-change="handleSelectionChange"
        >
      <el-table-column type="selection"
                       width="55" />
      <el-table-column type="index"
                       label="序号"
                       width="70" />

                             <el-table-column prop="activate" label="状态" min-width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.activate ? 'success' : 'danger'">
            {{ scope.row.activate ? '生效' : '失效' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="项目名称"
                       label="项目名称"
                       min-width="180">
        <template #default="scope">
          <el-tag type="primary">{{scope.row.projectName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="name"
                       label="名称"
                       min-width="120" />
      <el-table-column prop="specification"
                       label="规格"
                       min-width="120" />
      <el-table-column prop="material"
                       label="材质"
                       min-width="200" />
      <el-table-column prop="quantity"
                       label="数量"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.quantity }}
        </template>
      </el-table-column>
      <el-table-column prop="unit"
                       label="单位"
                       min-width="150" />
      <el-table-column prop="remark"
                       label="备注"
                       min-width="100" />
      <el-table-column prop="unitPrice"
                       label="含税单价"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.unitPrice ? formatPrice(scope.row.unitPrice) : formatPrice(0) }}
        </template>
      </el-table-column>
      <el-table-column prop="unitWeight"
                       label="单重"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.unitWeight ? formatNumber(scope.row.unitWeight) : formatNumber(0) }}
        </template>
      </el-table-column>
      <el-table-column prop="kgPrice"
                       label="公斤价"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.kgPrice ? formatPrice(scope.row.kgPrice) : formatPrice(0) }}
        </template>
      </el-table-column>
      <el-table-column prop="totalPrice"
                       label="总价"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.totalPrice ? formatPrice(scope.row.totalPrice) : formatPrice(0) }}
        </template>
      </el-table-column>
      <el-table-column prop="totalWeight"
                       label="总重"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.totalWeight ? formatNumber(scope.row.totalWeight) : formatNumber(0) }}
        </template>
      </el-table-column>

      <!-- <el-table-column prop="packingPrice"
                       label="包装费"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.packingPrice ? formatPrice(scope.row.packingPrice) : formatPrice(0) }}
        </template>
      </el-table-column>

      <el-table-column prop="transportationPrice"
                       label="运输费"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.transportationPrice ? formatPrice(scope.row.transportationPrice) : formatPrice(0) }}
        </template>
      </el-table-column>

      <el-table-column prop="implementationPrice"
                       label="实施费"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.implementationPrice ? formatPrice(scope.row.implementationPrice) : formatPrice(0) }}
        </template>
      </el-table-column>

      <el-table-column prop="otherPrice"
                       label="其他费用"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.otherPrice ? formatPrice(scope.row.otherPrice) : formatPrice(0) }}
        </template>
      </el-table-column> -->



      <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" show-overflow-tooltip>
        <template #default="scope">
          <span class="date-value">{{ scope.row.createTime ? dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createName" label="创建人" min-width="120" align="center" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ scope.row.createName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" min-width="180" align="center" show-overflow-tooltip>
        <template #default="scope">
          <span class="date-value">{{ scope.row.updateTime ? dayjs(scope.row.updateTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateName" label="更新人" min-width="120" align="center" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ scope.row.updateName || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作"
                       width="240"
                       fixed="right">
        <template #default="scope">
          <el-button type="success"
                     size="small"
                     link
                     @click="handleEdit(scope.row)"
                     :disabled="Number(scope.row.activate) !== 1"
                     icon="Edit"
                     v-permission="['specification:edit']">编辑</el-button>
          <el-button type="warning"
                     size="small"
                     link
                     @click="handleCustomEdit(scope.row)"
                     :disabled="Number(scope.row.activate) !== 1"
                     icon="Edit"
                     v-permission="['specification:edit']">非标编辑</el-button>
          <el-button type="primary"
                     size="small"
                     link
                     @click="handleView(scope.row)"
                     icon="View"
                     v-permission="['specification:view']">详情</el-button>
          <el-button type="danger" size="el-button--small" link @click="deleteOne(scope.row.id)" :disabled="scope.row.activate !== 1" icon="Delete" v-permission="['specification:edit']">删除</el-button>
        </template>
      </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination">
          <el-pagination 
            v-model:current-page="paginationData.currentPage"
            v-model:page-size="paginationData.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :background="true"
            layout="prev, pager, next, jumper,->,sizes,total"
            :total="paginationData.total"
            @current-change="getTableData"
            @size-change="getTableData"
          />
        </div>
      </el-card>
    </div>

    <!-- 分摊费用弹框 -->
    <sys-dialog :title="dialog.title"
                :width="dialog.width"
                :visible="dialog.visible"
                :height="dialog.height"
                @on-close="onClose"
                @on-confirm="submitShare">
      <template #content>
        <div class="share-form">
          <el-form :model="quotationShare"
                   label-width="120px">
            <el-form-item label="分摊类型"
                          required>
              <el-select v-model="quotationShare.type" filterable
                         placeholder="请选择分摊类型"
                         style="width: 100%">
                <el-option v-for="item in shareTypes"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="分摊金额"
                          required>
              <el-input-number v-model="quotationShare.price"
                               :precision="2"
                               :step="0.1"
                               :min="0"
                               style="width: 100%"
                               placeholder="请输入分摊金额" />
            </el-form-item>
          </el-form>
        </div>
      </template>
    </sys-dialog>

    <!-- 新增报价单展示弹窗 -->
    <sys-dialog
      :title="quotationDialog.title"
      :width="quotationDialog.width"
      :visible="quotationDialog.visible"
      :height="quotationDialog.height"
      @on-close="quotationDialog.visible = false" style="width: 730px;">
      <template #content>
        <div id="quotationContent">
          <div class="quotation-header">
            <div class="company-logo">
              <img src="../../../assets/logo.png" alt="公司logo" class="logo-image">
            </div>
            <div class="company-title">
              浙江中扬立库技术有限公司
            </div>
          </div>
          <div class="document-title">
            报价单
          </div>
          <div class="document-info">
          <div class="document-number"></div>
          <div class="document-number">NO.{{ Math.floor(Math.random() * 1000) + 1 }}</div>
          </div>
          <div class="document-info">
            <div class="document-number"></div>
            <div class="document-date">日期：{{ new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '/') }}</div>
          </div>

          <!-- 公司认证信息 -->
          <div class="certification-info">
            本公司专业生产制造现代仓储物流设备，已通过ISO9001质量体系认证，环境管理体系ISO14001
          </div>
          
          <!-- 客户与公司信息 -->
          <div class="info-section">
            <table class="info-table" border="1" cellspacing="0" cellpadding="0">
              <tr>
                <td class="label">客户名称：</td>
                <td class="value">{{ quotationPrintl?.customerName || '' }}</td>
                <td class="label">公司：</td>
                <td class="value">浙江中扬立库技术有限公司</td>
              </tr>
              <tr>
                <td class="label">联系人：</td>
                <td class="value">{{ quotationPrintl?.customerPerson || '' }}</td>
                <td class="label">联系人：</td>
                <td class="value">{{ quotationPrintl?.person || '' }}</td>
              </tr>
              <tr>
                <td class="label">联系方式：</td>
                <td class="value">{{ quotationPrintl?.customerPhone || '' }}</td>
                <td class="label">联系方式：</td>
                <td class="value">{{ quotationPrintl?.pPhone || '' }}</td>
              </tr>
              <tr>
                <td class="label">地址：</td>
                <td class="value">{{ quotationPrintl?.customerAddress || '' }}</td>
                <td class="label">地址：</td>
                <td class="value">{{ quotationPrintl?.address || '' }}</td>
              </tr>
              <tr>
                <td class="label">传真：</td>
                <td class="value">{{ quotationPrintl?.customerFax || '' }}</td>
                <td class="label">传真：</td>
                <td class="value">{{ quotationPrintl?.fax || '' }}</td>
              </tr>
              <tr>
                <td class="label">邮箱：</td>
                <td class="value">{{ quotationPrintl?.customerEmail || '' }}</td>
                <td class="label">邮箱：</td>
                <td class="value">{{ quotationPrintl?.email || '' }}</td>
              </tr>
            </table>
          </div>
          
          <!-- 备注区域 -->
          <div class="note-section">
            <div class="note-label">备注</div>
            <div class="note-content">
              <div class="note-row">
                <div class="note-title">货物参数：</div>
              </div>
              <div class="note-row">
                <div class="note-title">货物简要描述：</div>
              </div>
            </div>
          </div>
          
          <!-- 商品清单 -->
          <div class="items-section">
            <table class="quotation-table" border="1" cellspacing="0" cellpadding="0">
              <thead>
                <tr>
                  <th>序号</th>
                  <th>名称</th>
                  <th>规格型号</th>
                  <th>数量</th>
                  <th>单位</th>
                  <th>单价</th>
                  <th>小计</th>
                  <th>备注</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in quotationPrintl?.children || []" :key="index">
                  <td>{{ index + 1 }}</td>
                  <td>{{ item?.name || '' }}</td>
                  <td>{{ item?.specification || '' }}</td>
                  <td>{{ item?.quantity || 0 }}</td>
                  <td>{{ item?.unit || '' }}</td>
                  <td>¥ {{ item?.unitPrice ? item.unitPrice.toFixed(2) : '0.00' }}</td>
                  <td>{{ item?.totalPrice ? item.totalPrice.toFixed(2) : '0.00' }}</td>
                  <td>{{ item?.remark || '' }}</td>
                </tr>
                <!-- 计算总金额 -->
                <tr class="total-row">
                  <td colspan="2" class="text-right">总计大写：</td>
                  <td colspan="3">{{ convertToChinese(quotationPrintl?.children?.reduce((sum, item) => sum + (item?.totalPrice || 0), 0) || 0) }}</td>
                  <td>总计金额：</td>
                  <td colspan="2">{{ formatCurrency(quotationPrintl?.children?.reduce((sum, item) => sum + (item?.totalPrice || 0), 0) || 0) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
          
          <!-- 报价条款 -->
          <div class="terms-section">
            <ol class="terms-list">
                <li>1.以上报价根据国家税率涨幅含增值税发票；</li>
                <li>2.材质：Q355/Q235。强度标准：GB/50018-2016，屈服强度—235(N/mm2)  抗拉—205(N/mm2)  伸长率31%</li>
                <li>3.表面处理：脱脂磷化，后采用优质环氧树脂瑞士金马静电喷涂，执行标准：GB 15607-2008</li>
                <li>4.焊接标准.焊接标准：抗压—300(N/mm2) 抗拉—255(N/mm2) 抗剪—175(N/mm2)</li>
                <li>5.制造执行标准：CECS23-90(货架设计规范)；Jb/t5323-1991 (钢货架技术条件)；GBJ50017-2003 （高位仓库货架设计标准）；GBT 30675-2014 （阁楼式货架）</li>
                <li>6.报价单有效期：由于钢材价格波动比较大，此报价有效期：3天。</li>
                <li>7.钢材供应商；宝钢 日照钢铁 鞍钢 首钢及国内大型钢厂</li>
                <li>8.保修期：非人为因素保修1年</li>
                <li>9.付款方式：预付40%，发货付40%，全部到货验收后30天内付20%。</li>
                <li>10.以上报价按抗震6度计算，地震加速度为0.05g;</li>
              </ol>
              <div class="terms-note">
                注：付款方式为电汇，如承兑付款收取承兑汇票2.5%财务费用（半年期），乙方不接受商业承兑汇票。
              </div>
          </div>
          
          <div class="quotation-footer">
            <el-button type="primary" size="large" @click="printQuotation" style="padding: 12px 24px; font-size: 16px;" v-permission="['specification:view']">
              <el-icon style="margin-right: 5px;"><Document /></el-icon>
              打印报价单
            </el-button>
            <el-button type="success" size="large" @click="saveQuotation" style="padding: 12px 24px; font-size: 16px; margin-left: 10px;" v-permission="['specification:edit']">
              <el-icon style="margin-right: 5px;"><Document /></el-icon>
              保存报价单
            </el-button>
          </div>
        </div>
      </template>
    </sys-dialog>
  </el-main>

  <!-- 右侧表单占满整个屏幕 -->
  <el-main v-else-if="showForm">
    <BomForm :Id="Id"
             :mode="formMode"
             @save-success="handleSaveSuccess"
             @cancel="handleCancel" />
  </el-main>

  <!-- 非标结构件表单占满整个屏幕 -->
  <el-main v-else-if="showCustomForm">
    <CustomDetailForm :Id="customFormId"
                     :mode="customFormMode"
                     @save-success="handleCustomSaveSuccess"
                     @cancel="handleCustomCancel" />
  </el-main>

  <!-- 项目选择器组件 -->
  <ArchiveSelector v-model="projectSelectorVisible"
                   title="选择项目"
                   :search-fields="projectSearchFields"
                   :table-columns="projectTableColumns"
                   :fetch-data-api="getProjectList"
                   :multiple="false"
                   @confirm="handleProjectSelect" />

  <!-- 批量复制项目选择器组件 -->
  <ArchiveSelector v-model="batchCopyProjectSelectorVisible"
                   title="选择目标项目"
                   :search-fields="projectSearchFields"
                   :table-columns="projectTableColumns"
                   :fetch-data-api="getProjectList"
                   :multiple="false"
                   @confirm="handleBatchCopyProjectSelect" />

  <!-- 自定义导出弹窗 -->
  <sys-dialog 
    title="自定义导出" 
    :width="600" 
    :height="500" 
    :visible="exportDialog.visible"
    @on-close="closeExportDialog"
    @on-confirm="confirmCustomExport">
    <template #content>
      <div class="export-content">
        <!-- 搜索框 -->
        <div class="field-search">
          <el-input
            v-model="fieldSearchText"
            size="small"
            placeholder="搜索字段..."
            clearable
            style="width: 200px"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <!-- 全选操作按钮 -->
          <el-button 
            size="small" 
            type="primary" 
            @click="handleSelectAllFields(true)"
            :disabled="selectedExportFields.length === exportFieldList.length"
          >
            <el-icon><Switch /></el-icon>
            全选
          </el-button>
          <el-button 
            size="small" 
            @click="handleSelectAllFields(false)"
            :disabled="selectedExportFields.length === 0"
          >
            <el-icon><Refresh /></el-icon>
            清空
          </el-button>
        </div>

        <!-- 字段选择区域 -->
        <div class="field-selection">
          <div class="field-grid">
            <div 
              v-for="field in filteredExportFields" 
              :key="field.fieldName"
              class="field-item"
              :class="{ 'selected': selectedExportFields.includes(field.fieldName) }"
              @click="toggleField(field.fieldName)"
            >
              <el-icon v-if="selectedExportFields.includes(field.fieldName)" class="check-icon">
                <Check />
              </el-icon>
              <span class="field-name">{{ field.displayName }}</span>
            </div>
          </div>
        </div>

        <!-- 已选择字段统计 -->
        <div class="selection-summary">
          <el-text type="info">
            已选择 {{ selectedExportFields.length }} / {{ exportFieldList.length }} 个字段
          </el-text>
        </div>
      </div>
    </template>
  </sys-dialog>

  <!-- 批量复制弹窗 -->
  <sys-dialog
    :title="batchCopyDialog.title"
    :width="batchCopyDialog.width"
    :visible="batchCopyDialog.visible"
    :height="batchCopyDialog.height"
    @on-close="cancelBatchCopy"
    @on-confirm="confirmBatchCopy">
    <template #content>
      <div class="batch-copy-form">
        <el-form :model="batchCopySelectedProject" label-width="120px">
          <el-form-item label="已选择记录：">
            <el-text type="info">{{ multipleSelection.length }} 条记录</el-text>
          </el-form-item>
          <el-form-item label="目标项目：" required>
            <el-input 
              :model-value="batchCopySelectedProject ? batchCopySelectedProject.name : ''"
              placeholder="请选择目标项目"
              readonly
              class="selector-input"
              style="width: 100%"
            >
              <template #append>
                <el-button @click="openBatchCopyProjectSelector" v-permission="['specification:edit']">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-alert
              title="批量复制说明"
              type="info"
              description="将选中的记录完整复制到目标项目，包括主数据和所有子数据，仅项目信息会更改为新选择的项目。"
              show-icon
              :closable="false"
            />
          </el-form-item>
        </el-form>
      </div>
    </template>
  </sys-dialog>

  <!-- 导入结果对话框 -->
  <sys-dialog
    :visible="importResultDialog.visible"
    :title="`导入结果详情`"
    :width="600"
    :height="400"
    @on-close="closeImportResultDialog"
    @on-confirm="closeImportResultDialog"
  >
    <template #content>

      <!-- 导入结果摘要 -->
      <div class="import-result-summary">
        <el-alert
          :type="importResultDialog.result.successCount > 0 ? (importResultDialog.result.failCount > 0 ? 'warning' : 'success') : 'error'"
          :title="importResultDialog.result.successCount > 0 ? 
            (importResultDialog.result.failCount > 0 ? '部分导入成功' : '全部导入成功') : '导入失败'"
          :description="`成功：${importResultDialog.result.successCount}条，失败：${importResultDialog.result.failCount}条`"
          show-icon
          :closable="false"
        />
      </div>

      <!-- 导入统计 -->
      <div class="import-statistics" v-if="importResultDialog.result.failCount > 0">
        <el-row :gutter="16" style="margin-top: 20px;">
          <el-col :span="8">
            <el-statistic title="成功导入" :value="importResultDialog.result.successCount" />
          </el-col>
          <el-col :span="8">
            <el-statistic title="格式错误" :value="importResultDialog.result.formatErrorCount" />
          </el-col>
          <el-col :span="8">
            <el-statistic title="保存失败" :value="importResultDialog.result.saveErrorCount" />
          </el-col>
        </el-row>
      </div>

      <!-- 错误详情 -->
      <div v-if="importResultDialog.result.errorDetails && importResultDialog.result.errorDetails.length > 0" 
           class="error-details" style="margin-top: 20px;">
        <el-divider content-position="left">
          <span style="color: #f56c6c; font-weight: bold;">错误详情</span>
        </el-divider>
        <div class="error-list">
          <div v-for="(error, index) in importResultDialog.result.errorDetails" 
               :key="index" 
               class="error-item">
            <el-text type="danger" size="small">
              {{ error }}
            </el-text>
          </div>
        </div>
      </div>
    </template>
  </sys-dialog>
</template>


<style scoped lang="scss">
.el-pagination {
  margin-top: 10px;
  justify-content: flex-end;
}

.search-card {
  height: auto;
  margin-bottom: 20px;

  :deep(.el-card__body) {
    padding: 15px 20px;
  }

  .action-buttons-section {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #ebeef5;

    .button-group {
      display: flex;
      gap: 8px;
      align-items: center;

      &.batch-actions {
        flex: 1;
        justify-content: flex-start;
      }

      &.add-actions {
        justify-content: center;
      }

      &.import-export-actions {
        justify-content: flex-end;
      }
    }
  }

  .el-form {
    .el-form-item {
      margin-bottom: 10px;
      margin-right: 15px;

      &:last-child {
        margin-right: 0;
      }

      .el-input,
      .el-select {
        width: 220px;
      }

      // 按钮样式
      .action-btn {
        margin-right: 8px;
        margin-bottom: 5px;
        border-radius: 6px;
        font-weight: 500;
        transition: all 0.3s ease;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
        }

        .el-icon {
          margin-right: 4px;
        }
      }

      // 查询按钮
      .query-btn {
        background: linear-gradient(135deg, #409eff, #1989fa);
        border: none;
        color: white;

        &:hover {
          background: linear-gradient(135deg, #1989fa, #409eff);
        }
      }

      // 重置按钮
      .reset-btn {
        background: #f4f4f5;
        border: 1px solid #dcdfe6;
        color: #606266;

        &:hover {
          background: #ecf5ff;
          border-color: #c6e2ff;
          color: #409eff;
        }
      }

      // 新增按钮
      .add-btn {
        background: linear-gradient(135deg, #67c23a, #85ce61);
        border: none;

        &:hover {
          background: linear-gradient(135deg, #85ce61, #67c23a);
        }
      }

      // 新增非标结构件按钮
      .add-custom-btn {
        background: linear-gradient(135deg, #409eff, #1989fa);
        border: none;
        color: white;

        &:hover {
          background: linear-gradient(135deg, #1989fa, #409eff);
        }
      }

      // 导入按钮
      .import-btn {
        background: linear-gradient(135deg, #e6a23c, #f56c6c);
        border: none;
        color: white;

        &:hover {
          background: linear-gradient(135deg, #f56c6c, #e6a23c);
        }
      }

      // 导出按钮
      .export-btn {
        background: linear-gradient(135deg, #f56c6c, #ff7875);
        border: none;
        color: white;

        &:hover {
          background: linear-gradient(135deg, #ff7875, #f56c6c);
        }
      }

      // 自定义导出按钮
      .custom-export-btn {
        background: linear-gradient(135deg, #722ed1, #9c88ff);
        border: none;
        color: white;

        &:hover {
          background: linear-gradient(135deg, #9c88ff, #722ed1);
        }
      }

      // 下载模板按钮
      .template-btn {
        background: linear-gradient(135deg, #13c2c2, #36cfc9);
        border: none;
        color: white;

        &:hover {
          background: linear-gradient(135deg, #36cfc9, #13c2c2);
        }
      }
    }
  }
}

// 自定义导出弹窗样式
.export-content {
  padding: 20px;

  .field-search {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #e9ecef;

    .el-button {
      border-radius: 6px;
      font-weight: 500;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
      }
    }
  }

  .field-selection {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 15px;
    background: #fff;

    .field-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      gap: 10px;

      .field-item {
        display: flex;
        align-items: center;
        padding: 10px 12px;
        border: 2px solid #e4e7ed;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.3s ease;
        background: #fff;

        &:hover {
          border-color: #409eff;
          background: #f0f9ff;
          transform: translateY(-1px);
          box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
        }

        &.selected {
          border-color: #409eff;
          background: linear-gradient(135deg, #f0f9ff, #e6f7ff);
          color: #409eff;

          .check-icon {
            color: #409eff;
            margin-right: 8px;
            font-weight: bold;
          }
        }

        .field-name {
          font-size: 14px;
          font-weight: 500;
        }
      }
    }
  }

  .selection-summary {
    margin-top: 15px;
    text-align: center;
    padding: 10px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;

    .el-text {
      font-weight: 500;
    }
  }
}

.container {
  background: #f5f7fa;
  padding: 20px;
  min-height: calc(100vh - 60px);
}

.search-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 20px;
  
  .search-wrapper {
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  
  // 搜索表单区域
  .search-form-section {
    .demo-form-inline {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      align-items: flex-end;
      
      .el-form-item {
        margin-bottom: 0;
        
        .el-input {
          border-radius: 8px;
          
          .el-input__wrapper {
            transition: all 0.3s ease;
            
            &:hover {
              box-shadow: 0 0 0 1px #409eff inset;
            }
          }
        }
        
        .el-select {
          .el-input__wrapper {
            border-radius: 8px;
            transition: all 0.3s ease;
            
            &:hover {
              box-shadow: 0 0 0 1px #409eff inset;
            }
          }
        }
        
        &.search-buttons {
          .el-button {
            margin-right: 8px;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
            
            &:hover {
              transform: translateY(-1px);
              box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
            }
            
            &.search-btn {
              background: linear-gradient(135deg, #409EFF 0%, #1989fa 100%);
              border: none;
              color: white;
              
              &:hover {
                background: linear-gradient(135deg, #1989fa 0%, #409EFF 100%);
              }
            }
            
            &.reset-btn {
              background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
              border: none;
              color: white;
              
              &:hover {
                background: linear-gradient(135deg, #F78989 0%, #F56C6C 100%);
              }
            }
          }
        }
      }
    }
  }
  
  // 操作按钮区域
  .action-buttons-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
    
    .button-group {
      display: flex;
      gap: 10px;
      
      .el-button {
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }
        
        &.add-btn {
          background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
          border: none;
          color: white;
          padding: 10px 20px;
          
          &:hover {
            background: linear-gradient(135deg, #85CE61 0%, #67C23A 100%);
          }
        }
        
        &.template-btn {
          background: linear-gradient(135deg, #909399 0%, #B3B8C0 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #B3B8C0 0%, #909399 100%);
          }
        }
        
        &.import-btn {
          background: linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #F7BA2A 0%, #E6A23C 100%);
          }
        }
        
        &.export-btn {
          background: linear-gradient(135deg, #409EFF 0%, #1989fa 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #1989fa 0%, #409EFF 100%);
          }
        }
        
        &.custom-export-btn {
          background: linear-gradient(135deg, #409EFF 0%, #1989fa 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #1989fa 0%, #409EFF 100%);
          }
        }
        
        &.share-btn {
          background: linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #F7BA2A 0%, #E6A23C 100%);
          }
        }
        
        &.generate-btn {
          background: linear-gradient(135deg, #909399 0%, #B3B8C0 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #B3B8C0 0%, #909399 100%);
          }
        }
        
        &.batch-delete-btn {
          background: linear-gradient(135deg, #F56C6C 0%, #FF7875 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #FF7875 0%, #F56C6C 100%);
          }
        }
        
        &.batch-deactivate-btn {
          background: linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #F7BA2A 0%, #E6A23C 100%);
          }
        }
        
        &.batch-activate-btn {
          background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #85CE61 0%, #67C23A 100%);
          }
        }
        
        &.batch-copy-btn {
          background: linear-gradient(135deg, #409EFF 0%, #1989fa 100%);
          border: none;
          color: white;
          
          &:hover {
            background: linear-gradient(135deg, #1989fa 0%, #409EFF 100%);
          }
        }
      }
    }
  }
}

.list-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: none;
  
  :deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    
    .el-table__header-wrapper {
      .el-table__header {
        th {
          background: #f8fafc;
          color: #606266;
          font-weight: 600;
          border-bottom: 1px solid #e4e7ed;
        }
      }
    }
    
    .el-table__body-wrapper {
      .el-table__body {
        tr:hover {
          background-color: #f8fafc;
        }
        
        td {
          border-bottom: 1px solid #ebeef5;
        }
      }
    }
    
    .el-button {
      border-radius: 6px;
      
      &.el-button--small {
        padding: 5px 12px;
      }
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  
  :deep(.el-pagination) {
    .el-pager li {
      border-radius: 6px;
    }
    
    .btn-prev,
    .btn-next {
      border-radius: 6px;
    }
  }
}

.share-form {
  padding: 20px;

  :deep(.el-form-item__label) {
    font-weight: bold;
  }

  :deep(.el-input-number) {
    width: 100%;
  }
}

.quotation-content {
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .quotation-header {
    position: relative;
    margin-bottom: 15px;
    text-align: center;
    display: flex;
    flex-direction: column;

    .company-logo {
      position: absolute;
      top: 0;
      right: 0;
      text-align: right;

      .logo-image {
        max-width: 80px;
        height: auto;
      }
    }

    .company-title {
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .document-title {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .document-info {
      display: flex;
      justify-content: space-between;
      width: 100%;

      .document-number {
        font-weight: bold;
      }

      .document-date {
        font-size: 14px;
      }
    }
  }

  .certification-info {
    text-align: center;
    color: #e41e2b;
    font-size: 14px;
    margin-bottom: 15px;
    border-bottom: 1px solid #dcdfe6;
    padding-bottom: 10px;
  }

  .info-section {
    margin-bottom: 15px;

    .info-table {
      width: 100%;
      border-collapse: collapse;

      td {
        padding: 8px;
        border: 1px solid #000;

        &.label {
          width: 15%;
          text-align: right;
          font-weight: bold;
        }

        &.value {
          width: 35%;
        }
      }
    }
  }

  .note-section {
    margin-bottom: 15px;

    .note-label {
      font-weight: bold;
      margin-bottom: 5px;
    }

    .note-content {
      border: 1px solid #000;
      padding: 10px;

      .note-row {
        display: flex;
        margin-bottom: 10px;

        .note-title {
          font-weight: bold;
          width: 150px;
        }
      }
    }
  }

  .items-section {
    margin-bottom: 15px;

    .quotation-table {
      width: 100%;
      border-collapse: collapse;

      th, td {
        padding: 8px;
        border: 1px solid #000;
        text-align: center;
      }

      thead {
        background-color: #f0f0f0;

        th {
          font-weight: bold;
        }
      }

      .total-row {
        background-color: #f0f0f0;
        font-weight: bold;

        .text-right {
          text-align: right;
        }
      }
    }
  }

  .terms-section {
    .terms-list {
      margin-left: 20px;
      padding-left: 0;

      li {
        margin-bottom: 5px;
        font-size: 14px;
      }
    }

    .terms-note {
      margin-top: 10px;
      font-size: 14px;
    }
  }

  .quotation-footer {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .total-amount {
      margin-left: auto; /* 确保总价在右侧 */
      font-size: 18px;
      font-weight: bold;
      color: #303133;
      text-align: right;
    }

    .print-area {
      .el-button {
        padding: 10px 24px;
        font-size: 14px;
      }
    }
  }
}

@media print {
  body {
    width: 100%;
    margin: 0;
    padding: 0;
  }

  .quotation-content {
    padding: 0;
    box-shadow: none;

    .quotation-header {
      .quotation-logo {
        .logo-image {
          max-width: 120px;
        }
      }

      .quotation-date-number {
        display: flex;
        justify-content: space-between;
        width: 100%;

        .date {
          text-align: left;
        }

        .number {
          text-align: right;
        }
      }

      .quotation-info {
        h2 {
          font-size: 20px;
        }
      }
    }

    .quotation-table {
      font-size: 12px;

      th, td {
        padding: 6px;
      }
    }

    .quotation-footer {
      display: flex;
      justify-content: flex-end !important;

      .print-area {
        display: none;
        visibility: hidden;
      }

      .total-amount {
        margin-left: auto;
        text-align: right;
        font-size: 16px;
      }
    }
  }
}

#quotationContent {
  background-color: white;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-width: 900px;
  margin: 0 auto;
  border: 1px solid #dcdfe6;
  font-family: SimSun, serif;
}

.quotation-header {
  position: relative;
  margin-bottom: 20px;
  text-align: center;
}

.company-logo {
  position: absolute;
  top: 0;
  right: 0;
  text-align: right;
}

.company-logo img {
  max-width: 80px;
  height: auto;
}

.action-bar {
  margin-bottom: 20px;
  text-align: right;
  
  @media print {
    display: none;
  }
}

.company-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}

.document-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}

.document-info {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
}

.certification-info {
  text-align: center;
  color: #e41e2b;
  font-size: 14px;
  margin-bottom: 15px;
  border-bottom: 1px solid #dcdfe6;
  padding-bottom: 10px;
}

.info-section {
  margin-bottom: 15px;
}

.info-table {
  width: 100%;
  border-collapse: collapse;
}

.info-table td {
  padding: 8px;
  border: 1px solid #000;
}

.info-table .label {
  width: 15%;
  text-align: right;
  font-weight: bold;
}

.info-table .value {
  width: 35%;
}

.note-section {
  margin-bottom: 15px;
}

.note-label {
  font-weight: bold;
  margin-bottom: 5px;
}

.note-content {
  border: 1px solid #000;
  padding: 10px;
}

.note-row {
  display: flex;
  margin-bottom: 10px;
}

.note-title {
  font-weight: bold;
  width: 150px;
}

.items-section {
  margin-bottom: 15px;
}

.quotation-table {
  width: 100%;
  border-collapse: collapse;
}

.quotation-table th, .quotation-table td {
  padding: 8px;
  border: 1px solid #000;
  text-align: center;
}

.quotation-table thead th {
  background-color: #f0f0f0;
  font-weight: bold;
}

.quotation-table .total-row {
  background-color: #f0f0f0;
  font-weight: bold;
}

.quotation-table .total-row .text-right {
  text-align: right;
}

.terms-section {
  margin-top: 15px;
}

.terms-list {
  margin-left: 20px;
  padding-left: 0;
}

.terms-list li {
  margin-bottom: 5px;
  font-size: 14px;
}

.terms-note {
  margin-top: 10px;
  font-size: 14px;
}

// 导入结果对话框样式
.import-result-summary {
  margin-bottom: 20px;
}

.import-statistics {
  .el-statistic {
    text-align: center;
  }
}

.error-details {
  max-height: 300px;
  overflow-y: auto;
  
  .error-list {
    background-color: #fef0f0;
    border: 1px solid #fbc4c4;
    border-radius: 4px;
    padding: 12px;
    
    .error-item {
      margin-bottom: 8px;
      padding: 4px 0;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

// 批量复制表单样式
.batch-copy-form {
  padding: 20px;

  :deep(.el-form-item__label) {
    font-weight: bold;
  }

  .selector-input {
    :deep(.el-input__wrapper) {
      border-radius: 8px;
      transition: all 0.3s ease;
      
      &:hover {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }
  }

  .el-alert {
    margin-top: 10px;
  }
}


</style>
